package com.yykj.user.center.server.controller.patient;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yykj.common.vo.PageData;
import com.yykj.common.vo.ResultVO;
import com.yykj.tencent.im.client.feign.TencentImFeignClient;
import com.yykj.tencent.im.client.form.UserProfileForm;
import com.yykj.user.center.server.dto.ConsultationDoctorDTO;
import com.yykj.user.center.server.dto.ConsultationInfoDTO;
import com.yykj.user.center.server.dto.ConsultationInfoOrderDTO;
import com.yykj.user.center.server.emun.CustomMessageType;
import com.yykj.user.center.server.form.*;
import com.yykj.user.center.server.model.ConsultationInfoOrder;
import com.yykj.user.center.server.model.Patient;
import com.yykj.user.center.server.repository.patient.PatientRepository;
import com.yykj.user.center.server.service.MedicalRecordService;
import com.yykj.user.center.server.service.patient.ConsultationInfoService;
import com.yykj.user.center.server.service.patient.PaymentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenl
 * @version 1.0
 * @date 2021/11/6 14:17
 */
@Slf4j
@Api(tags = "问诊信息相关接口")
@RestController
@RequestMapping("/api/consultation")
@SuppressWarnings("unchecked")
public class ConsultationOrderController {
    @Autowired
    private ConsultationInfoService consultationInfoService;
    @Autowired
    private MedicalRecordService medicalRecordService;

    @Autowired
    private PaymentService paymentService;

    @PostMapping("/create")
    @ApiOperation(value = "生成问诊订单", notes = "生成问诊订单")
    public ResultVO create(@Valid @RequestBody AddConsultationOrderForm addConsultationInfoForm) {
        return ResultVO.success(consultationInfoService.create(addConsultationInfoForm));
    }

    @PostMapping("/again")
    @ApiOperation(value = "续方", notes = "续方")
    public ResultVO again(@Valid @RequestBody AddAgainConsultationOrderForm addAgainConsultationOrderForm) {
        return ResultVO.success(consultationInfoService.again(addAgainConsultationOrderForm));
    }

    @GetMapping("/consultationDoctors")
    @ApiOperation(value = "个人中心-已问诊医生", notes = "个人中心-已问诊医生")
    public ResultVO<List<ConsultationDoctorDTO>> consultationDoctors() {
        return ResultVO.success(consultationInfoService.consultationDoctors());
    }

    @PostMapping("/updateState")
    @ApiOperation(value = "更改问诊订单的状态", notes = "更改问诊订单的状态")
    public ResultVO updateState(@Valid @RequestBody UpdateConsultationOrderStateForm updateConsultationOrderStateForm) {
        return ResultVO.success(consultationInfoService.updateState(updateConsultationOrderStateForm));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "patientCardId", value = "就诊卡ID", required = false, dataType = "String"),
            @ApiImplicitParam(name = "state", value = "状态：0生成订单 1待接诊  2问诊中  3已完成 4已退款", required = false, dataType = "Integer"),
    })
    @ApiOperation(value = "个人中心-我的问诊", notes = "个人中心-我的问诊")
    @GetMapping("/consultationList")
    public ResultVO consultationList(@RequestParam(value = "patientCardId", required = false) String patientCardId,
                                     @RequestParam(value = "state", required = false) Integer state) {
        return ResultVO.success(consultationInfoService.consultationList(patientCardId, state));
    }

    @PostMapping("/cancel")
    @ApiOperation("结束问诊")
    public ResultVO cancel(@Valid @RequestBody CancelConsultationForm cancelConsultationForm) {
        return ResultVO.success(consultationInfoService.cancel(cancelConsultationForm));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "size", value = "每页显示的条数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "startDate", value = "开始日期", required = false, dataType = "String"),
            @ApiImplicitParam(name = "endDate", value = "结束日期", required = false, dataType = "String"),
            @ApiImplicitParam(name = "doctorName", value = "医生姓名", required = false, dataType = "String"),
            @ApiImplicitParam(name = "patientName", value = "患者姓名", required = false, dataType = "String"),
            @ApiImplicitParam(name = "mobile", value = "手机号", required = false, dataType = "String"),
            @ApiImplicitParam(name = "orderNo", value = "订单编号", required = false, dataType = "String"),
            @ApiImplicitParam(name = "orderType", value = "订单类型：11、图文问诊 12、语音问诊 13、视频问诊 14、检查订单 15、检验订单", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "endType", value = "结束方式：0手动结束 自动结束", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "state", value = "状态：1待接诊  2问诊中  3已完成", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "refundStatus", value = "患者退款状态-1:未退款,0:申请退款,1:已退款,2:退款失败", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "payStatus", value = "患者支付状态-1:取消,0:待支付,1:已支付", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "hospitalId", value = "医院Id", required = false, dataType = "Integer"),
    })
    @ApiOperation(value = "问诊列表", notes = "问诊列表")
    @GetMapping("/list")
    public ResultVO<PageData<ConsultationInfoOrderDTO>> list(@RequestParam(value = "current", required = false, defaultValue = "0") Integer current,
                                                             @RequestParam(value = "size", required = false, defaultValue = "1000") Integer size,
                                                             @RequestParam(value = "startDate", required = false) String startDate,
                                                             @RequestParam(value = "endDate", required = false) String endDate,
                                                             @RequestParam(value = "doctorName", required = false) String doctorName,
                                                             @RequestParam(value = "patientName", required = false) String patientName,
                                                             @RequestParam(value = "mobile", required = false) String mobile,
                                                             @RequestParam(value = "orderNo", required = false) String orderNo,
                                                             @RequestParam(value = "orderType", required = false) Integer orderType,
                                                             @RequestParam(value = "endType", required = false) Integer endType,
                                                             @RequestParam(value = "state", required = false) Integer state,
                                                             @RequestParam(value = "refundStatus", required = false) Integer refundStatus,
                                                             @RequestParam(value = "payStatus", required = false) Integer payStatus,
                                                             @RequestParam(value = "hospitalId", required = false) Integer hospitalId) {
        return ResultVO.success(consultationInfoService.list(current, size, startDate, endDate, doctorName, patientName, mobile, orderNo, orderType, endType, state, refundStatus, payStatus, hospitalId));
    }

    @GetMapping("/info")
    @ApiOperation(value = "最新的问诊详情", notes = "最新的问诊详情")
    public ResultVO<ConsultationInfoDTO> info(@RequestParam(value = "accountId", required = false) String accountId,
                                              @RequestParam(value = "doctorId", required = false) String doctorId,
                                              @RequestParam(value = "consultationInfoId", required = false) String consultationInfoId,
                                              @RequestParam(value = "prescriptionId", required = false) String prescriptionId) {
        return ResultVO.success(consultationInfoService.info(accountId, doctorId, consultationInfoId, prescriptionId));
    }

    @GetMapping("/auth")
    @ApiOperation(value = "授权", notes = "授权")
    public ResultVO auth(@RequestParam(value = "consultationId", required = false) String consultationId,
                         @RequestParam(value = "type", required = false) int type) {
        consultationInfoService.auth(consultationId, type);
        return ResultVO.success();
    }

    @GetMapping("/statistics")
    @ApiOperation(value = "问诊统计", notes = "问诊统计")
    public ResultVO info(
            @RequestParam(value = "doctorId", required = true) String doctorId
    ) {
        return ResultVO.success(consultationInfoService.statistics(doctorId));
    }

    @Autowired
    PatientRepository patientRepository;
    @Autowired
    TencentImFeignClient tencentImFeignClient;

    @GetMapping("/resolveImAccount")
    public ResultVO resolveImAccount() {
        List<Patient> all = this.patientRepository.findAll();
        for(Patient patient : all){
            String tencentAccountId = patient.getTencentAccountId();
            if(!StringUtils.isEmpty(tencentAccountId)){
                UserProfileForm userProfileForm = UserProfileForm.builder()
                        .client("patient")
                        .fromAccount(patient.getTencentAccountId())
                        .name(patient.getNickName())
                        .image(patient.getAvatar())
                        .hospital("")
                        .depName("")
                        .officer("")
                        .phone(patient.getMobile()).build();
                try {
                    this.tencentImFeignClient.setProfile(userProfileForm);
                }catch (Exception e){

                }

            }
        }
        return ResultVO.success();
    }

    @PostMapping("/prescription/create")
    @ApiOperation(value = "绑定处方会诊")
    public ResultVO<String> prescriptionBinding(@RequestBody @Valid PrescriptionBindingForm prescriptionBindingForm) {

        ConsultationInfoOrder consultationInfoOrder = medicalRecordService.create(prescriptionBindingForm.getMedicalRecord());
        if (consultationInfoOrder != null) {
            Map<String, Object> finishMap = new HashMap();
            finishMap.put("type", CustomMessageType.orderFinish.getCode());
            finishMap.put("data", consultationInfoOrder.getId());
            paymentService.sendPayedMsg(consultationInfoOrder.getDoctorTencentAccountId(), consultationInfoOrder.getPatientTencentAccountId(), JSON.toJSONString(finishMap, SerializerFeature.WriteNullStringAsEmpty), 1);
            return ResultVO.success(consultationInfoService.prescriptionBinding(prescriptionBindingForm));
        }
        return ResultVO.error(null);
    }
}